<?php


namespace app\task\job;


use app\common\model\SchoolModel;
use app\common\service\redis\PoolRedis;
use app\common\service\sim\OpenSim;
use app\model\AdminSchool;
use app\model\AdminStaff;
use app\model\AdminStaffIcCard;
use app\util\Strs;
use app\util\Tools;
use think\facade\Log;
use think\queue\Job;

class SyncPhoneSeidJob
{
    /**
     * 队列入口
     * @param Job $job
     * @param $data
     */
    public function fire(Job $job, $data)
    {
        $isJobDone = $this->handle($data);
        if ($isJobDone) {
            //如果任务执行成功，记得删除任务
            $job->delete();
        }else{
            //通过这个方法可以检查这个任务已经重试了几次了
            if ($job->attempts() > 3){
                $job->delete();
            }
        }
    }

    /**
     * 处理
     * @param $data
     * @return bool
     * @desc sim卡调用获取seid
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle($data)
    {
        $phone = $data['phone'];
        try {
            $staff = AdminStaff::where([
                'phone' => $phone,
                'is_delete' => 0,
                'status' => AdminStaff::AUDIT_PASS
            ])->find();
            if (!$staff) {
                return true;
            }
            $estateId = $this->getEstateId($staff->school_id);
            if (!$estateId) {
                return true;
            }
            $transactionId = Strs::randString(12, 1);
            $params = [
                'phone' => $phone,
                'estateId' => $estateId,
                'transactionId' => $transactionId
            ];
            $sim = (new OpenSim())->setUrl('/simipass/api/estate/door/platformEstateOpen')
                ->setMethod('POST');
            $result = $sim->setParams($params)->request();
            if ($sim->errorCode() == '1003') {
                $result = $sim->setParams($params)->request();
            }
            $sim->close();
            if ($result['resultCode'] == '0000') {
//                Log::error('---------- 平台用户开通：seid获取成功 ----------');
//                Log::error(json_encode($result, JSON_UNESCAPED_UNICODE));
                if (empty($result['seid'])) {
                    return true;
                }
                $old_sim_card = $staff->sim_card;
                $new_sim_card = $result['seid'];
                // 新的与旧的不一样
                if($old_sim_card != $new_sim_card) {
                    $staff->sim_card = $new_sim_card;
                    if ($staff->save()) {
//                    $redis = PoolRedis::instance();
//                    $redis->hDel("smartCards", $old_sim_card);
//                    $redis->hSetNx("smartCards", $new_sim_card, $staff->id);
                        $update['sim_uid'] = $staff->sim_card;
                        $update['sim_activate_time'] = 0;
                        AdminStaffIcCard::update($update, [
                            'staff_id' => $staff->id,
                            'school_id' => $staff->school_id,
                            'is_delete' => 0
                        ]);
                    }
                }
            } else {
                Log::error('---------- 平台用户开通：seid请求参数 ----------');
                Log::error(json_encode($sim->getParams(), JSON_UNESCAPED_UNICODE));
                Log::error('---------- 平台用户开通：seid获取失败 ----------');
                Log::error(json_encode($result, JSON_UNESCAPED_UNICODE));
            }
            return true;
        } catch (\Exception $e) {
            Log::error($e->getTraceAsString());
            return false;
        }
    }

    private function getEstateId($school_id)
    {
        $school = SchoolModel::getSchool($school_id);
        if ($school->estate_id) {
            return $school->estate_id;
        }
        $transactionId = Strs::randString(12, 1);
        $params = [
            'province' => str_replace(['省','市'],'', trim($school->province)),
            'city' => str_replace('市','', trim($school->city)),
            'area' => str_replace('区','', trim($school->area)),
            'estateName' => $school->name,
//            'province' => '广东',
//            'city' => '广州',
//            'area' => '天河',
//            'estateName' => "天河".Tools::get_millisecond(),
            'doorType' => "1",
            'transactionId' => $transactionId
        ];
        $sim = (new OpenSim())
            ->setUrl('/simipass/api/estate/door/estateInfoSync')
            ->setMethod('POST');
        $result = $sim->setParams($params)->request();
        if (isset($result['resultCode']) && $result['resultCode'] == '1003') {
            $result = $sim->setParams($params)->request();
        }
        $sim->close();
        Log::error('---------- 平台用户开通：estateId请求参数 ----------');
        Log::error(json_encode($sim->getParams(), JSON_UNESCAPED_UNICODE));
        if (isset($result['resultCode']) && $result['resultCode'] == '0000') {
            Log::error('---------- 平台用户开通：estateId获取成功 ----------');
            Log::error(json_encode($result, JSON_UNESCAPED_UNICODE));
            //保存 estateId
            $school->estate_id = $result['estateId'];
            $school->save();
            return $result['estateId'];
        }
        Log::error('---------- 平台用户开通：estateId获取失败 ----------');
        Log::error(json_encode($result, JSON_UNESCAPED_UNICODE));
        return null;
    }
}